import time
import ssd1306
import neopixel
from machine import I2C, Pin, PWM, ADC

p2 = Pin(2, Pin.OUT)
# blink function
def blink(n,t):
    for i in range(n):
        p2.value(0)
        time.sleep(t)
        p2.value(1)
        time.sleep(t)

blink(3,0.2)

print("create display and button")

# display
i2c = I2C(scl=Pin(2), sda=Pin(14)) # D4 D5
display = ssd1306.SSD1306_I2C(128, 64, i2c)
# flip screen
display.write_cmd(0xA0) # SEGREMAP
display.write_cmd(0xC0) # COMSCANINC

# touch sensor D8 GPIO15
button = Pin(15, Pin.IN)
buttonDownLevel = 1

# beeper D7 GPIO13
beeper = PWM(Pin(13, Pin.OUT), freq=600, duty=0) 
def beep(t=2,freq=600,duty=512):
	beeper.duty(duty) 
	time.sleep_ms(t)
	beeper.duty(0)

# distance sensor
trigPin = Pin(5, Pin.OUT) #GPIO5 D1
echoPin = Pin(4, Pin.IN)  #GPIO4 D2
# Return distance (cm). 
def measureDist():
	trigPin.on()
	time.sleep_us(15)
	trigPin.off()

	t0 = time.ticks_us()
	# wait for 1
	while not echoPin.value():
		if  time.ticks_diff(time.ticks_us(), t0)>5000:  # 5ms
			# print("Check Pin.")
			return 0

	t1= time.ticks_us()  # time of rising edge
	# wait for 0
	while echoPin.value():
		# limit measure distance 0.5m. 1/314=2.941ms 
		if  time.ticks_diff(time.ticks_us(), t1)>2941:
			# print("Out of range.")
			return 50
	delta = time.ticks_diff(time.ticks_us(), t1) # us
	return int(delta*0.017) #cm

# light sensor  A0
adc = ADC(0)
def measureLight():
	return adc.read()

# setup led
print("Setup Led")
# D6 GPIO12
led = neopixel.NeoPixel(Pin(12), 8) # D6
led[0] = (255, 0, 0) # set to red, full brightness
led[1] = (0, 128, 0) # set to green, half brightness
led[2] = (0, 0, 64)  # set to blue, quarter brightness
led.write()
time.sleep(0.5)

def turnLed(cmd):
    if cmd == 1:
        d = (0,0,64)
    else:
        d = (0,0,0)
    for i in range(8):
        led[i] = d
    led.write()

turnLed(0)

#  Welcom screen
def welcome(msg):
	display.fill(0)
	display.hline(0,0,127,1)
	display.hline(0,63,127,1)
	display.vline(0,0,63,1)
	display.vline(127,0,63,1)
	display.text(msg, 10, 10, 1)

	frame = 1
	for i in range(25):
		display.text("o", 55+2,   23, 1)
		# erase
		display.text("M", 55, 23+8, 0)
		display.text("V", 55, 23+8, 0)
		# draw
		if(frame == 1):
			display.text("M", 55, 23+8, 1)
		else:
			display.text("V", 55, 23+8, 1)
		frame = not frame
		display.show()
		time.sleep_ms(20)

# draw an image from buf
def drawImage(rows, cols, buf, offset_col, offset_row):
	buf_index = 0 
	for y in range(rows):
		Y = y + offset_row
		BUF_index = 128*Y + offset_col
		if BUF_index > 1023:
			return
		for x in range(cols):
			display.buffer[BUF_index + x] = buf[buf_index]
			buf_index += 1

# draw a picture from a img file
def drawImageFile(imgFile,offset_col, offset_row):
	try:
		f = open(imgFile,'rb')
		data = f.read(1)
		rows=int.from_bytes(data, "big")
		data = f.read(1)
		cols=int.from_bytes(data, "big")
		buf=f.read(rows*cols)
		f.close()
		drawImage(rows,cols,buf,offset_col, offset_row)
		del(buf)
	except OSError as er:
		print(er)
